package com.roc.template.shiro.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.roc.template.mongo.model.User;
import com.roc.template.mongo.service.UserService;
import com.roc.template.shiro.jwt.JwtUtil;
import com.roc.template.base.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class ShiroInterceptor implements HandlerInterceptor {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        logger.info("token is "+ token);
        if(token!=null) {
            String username = JwtUtil.getUsername(token);
            User byUsername = userService.getByUserName(username);
            if(!JwtUtil.verify(token, byUsername.getUserName(), byUsername.getPassWord())) {
                Result result = new Result(false, "会话失效，请重新进入应用", "401", "");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.print(JSONObject.toJSONString(result));
                printWriter.close();
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
